import React, { useReducer } from 'react'
import Goods from '../views/Goods'
import context from './context'

// 方案一：useReducer+content实现全局状态
let userInfo = localStorage.getItem('userInfo')
try {
    userInfo = JSON.parse(userInfo) || {}
} catch (err) {
    userInfo = {}
}

// 购物车数据实现持久化：刷新时存本地存储获取数据
let cartlist = localStorage.getItem('cartlist')
try {
    cartlist = JSON.parse(cartlist) || []
} catch (err) {
    cartlist = []
}

const initState = {
    userInfo,
    cartlist,
}
const reducer = function (state, {type,payload}) {
    let newCartlist
    // {type:string,payload:object}
    switch (type) {
        // {type:'login',userInfo:data.data}
        case 'login':
            localStorage.setItem('userInfo',JSON.stringify(payload))
            return {
                ...state,
                userInfo: payload
            }
        case 'logout':
            localStorage.removeItem('userInfo')
            return {
                ...state,
                userInfo: {}
            }
        // {type:'addTocart',payload:{}}
        case 'addtocart':
            newCartlist = [payload,...state.cartlist]
            localStorage.setItem('cartlist',JSON.stringify(newCartlist))
            return {
                ...state,
                cartlist:newCartlist
            }
        // {type:'changeqty',payload:{_id,qty}}
        case 'changeqty':
            newCartlist = state.cartlist.map(item=>{
                if(item._id === payload._id){
                    item.qty = payload.qty
                }
                return item;
            })
            localStorage.setItem('cartlist',JSON.stringify(newCartlist))
            return {
                ...state,
                cartlist:newCartlist
            }
        // {type:'remove',payload:{_id}}
        case 'remove':
            newCartlist = state.cartlist.filter(item=>item._id!==payload._id)
            localStorage.setItem('cartlist',JSON.stringify(newCartlist))
            return {
                ...state,
                cartlist:newCartlist
            }

        case 'clear':
            newCartlist = []
            localStorage.remove('cartlist')
            return {
                ...state,
                cartlist:newCartlist
            }

    }
}


export function Provider({ children }) {
    const [{ userInfo,cartlist }, dispatch] = useReducer(reducer, initState)
    return (
        <context.Provider value={{ userInfo,cartlist, dispatch }}>
            {children}
        </context.Provider>
    )
}